package top.january.test;

import ohos.aafwk.ability.*;
import ohos.ace.ability.AceAbility;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.event.commonevent.*;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.audio.AudioManager;
import ohos.media.audio.AudioRemoteException;
import ohos.rpc.RemoteException;
import ohos.utils.zson.ZSONObject;
import ohos.aafwk.content.Intent;

import java.util.Map;

public class MainAbility extends AceAbility {
    ProviderFormInfo formInfo;
    static final long INVALID_FORM_ID = -1;
    static final long UNINITIALIZED_FORM_ID = -999;
    static final String EMPTY_STRING = "";
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbility");

    static final String FIELD_BUTTON_BACKGROUND = "button_background";
    static final String FIELD_STATUS_TEXT = "status_text";
    static final String FIELD_MUSIC_VOL_STYLE = "music_vol_style";
    static final String FIELD_RING_VOL_STYLE = "ring_vol_style";
    static final String VOL_ON_COLOR = "#0074D8";
    static final String VOL_OFF_COLOR = "#405A75";

    long m_formId = UNINITIALIZED_FORM_ID;
    private Preferences m_preferences = null;
    private DatabaseHelper m_databaseHelper = null;

    CommonEventSubscriber m_subscriber;

    @Override
    public void onStart(Intent intent) {
        // 当对应的js组件名称不为default时，必须显示指定其名称
        setInstanceName("MainAbility");
        MaininternalAbility.register(this);
        super.onStart(intent);
        // super.setMainRoute(MainAbilitySlice.class.getName());
        subscribeCommonEvent();
        m_formId = getFormId();
    }



    @Override
    public void onStop() {
        super.onStop();
        unsubscribeCommonEvent();
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        long formId;
        if (intent == null) {
            return new ProviderFormInfo();
        }
        // 获取卡片id
        formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);

        // 获取卡片名称
        String formName = EMPTY_STRING;
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_NAME_KEY)) {
            formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        }

        FormBindingData formBindingData = new FormBindingData(getVolumeFormData());
        formInfo = new ProviderFormInfo();
        formInfo.setJsBindingData(formBindingData);

        if (m_formId == UNINITIALIZED_FORM_ID) {
            m_formId = getFormId();
        }
        if (m_formId == INVALID_FORM_ID) {
            setFormId(formId);
        }

        HiLog.debug(LABEL_LOG, "create card %{public}d", formId);
        return formInfo;
    }

    int getVolume(String stream)  {
        AudioManager m_audioManager = new AudioManager();
        AudioManager.AudioVolumeType volumeType;
        if ("music".equals(stream)) {
            volumeType = AudioManager.AudioVolumeType.STREAM_MUSIC;
        } else {
            volumeType = AudioManager.AudioVolumeType.STREAM_RING;
        }
        int maxVolume = 100;
        int minVolume = 0;
        float current_volume = 0;
        try {
            maxVolume = m_audioManager.getMaxVolume(volumeType);
            minVolume = m_audioManager.getMinVolume(volumeType);
            current_volume = m_audioManager.getVolume(volumeType);
        } catch (AudioRemoteException e) {
            e.printStackTrace();
        }
        float percent =  (current_volume - minVolume) / (maxVolume - minVolume);
        return (int)(percent * 100);
    }

    void setVolume(String stream, int volume) {
        AudioManager m_audioManager = new AudioManager();
        AudioManager.AudioVolumeType volumeType;
        if ("music".equals(stream)) {
            volumeType = AudioManager.AudioVolumeType.STREAM_MUSIC;
        } else {
            volumeType = AudioManager.AudioVolumeType.STREAM_RING;
        }
        int maxVolume = 100;
        int minVolume = 0;
        try {
            maxVolume = m_audioManager.getMaxVolume(volumeType);
            minVolume = m_audioManager.getMinVolume(volumeType);
            float percent = (((float)volume / 100) * (maxVolume - minVolume) + minVolume);
            m_audioManager.setVolume(volumeType, (int)percent);
        } catch (AudioRemoteException e) {
            e.printStackTrace();
        }
    }

    boolean getMuteState() {
        boolean result = false;
        AudioManager m_audioManager = new AudioManager();
        try {
            result = m_audioManager.isMute(AudioManager.AudioVolumeType.STREAM_MUSIC) && m_audioManager.isMute(AudioManager.AudioVolumeType.STREAM_RING);
        } catch (AudioRemoteException e) {
            e.printStackTrace();
            HiLog.debug(LABEL_LOG, "Failed to get mute state");
        }
        return result;
    }

    void switch_mute() {
        AudioManager m_audioManager = new AudioManager();
        if (getMuteState() == true) {
            m_audioManager.unmute(AudioManager.AudioVolumeType.STREAM_MUSIC);
            m_audioManager.unmute(AudioManager.AudioVolumeType.STREAM_RING);
        } else {
            m_audioManager.mute(AudioManager.AudioVolumeType.STREAM_MUSIC);
            m_audioManager.mute(AudioManager.AudioVolumeType.STREAM_RING);
        }
    }

    @Override
    protected void onDeleteForm(long formId) {
        super.onDeleteForm(formId);
        if (m_formId == formId) {
            setFormId(-1);
        }
    }

    @Override
    protected void onUpdateForm(long formId) {
        HiLog.debug(LABEL_LOG, "update form, id %d", formId);
        updateVolumeForm(formId);

    }
    
    String getVolStyleFromVol(int vol) {
        return vol + "%";
    }

    ZSONObject getVolumeFormData() {
        ZSONObject zsonObject = new ZSONObject();
        if (getMuteState() == true) {
            zsonObject.put(FIELD_STATUS_TEXT, "OFF");
            zsonObject.put(FIELD_BUTTON_BACKGROUND, VOL_OFF_COLOR);
        } else {
            zsonObject.put(FIELD_STATUS_TEXT, "ON");
            zsonObject.put(FIELD_BUTTON_BACKGROUND, VOL_ON_COLOR);
        }
        int music_vol = getVolume("music");
        int ring_vol = getVolume("ring");
        zsonObject.put(FIELD_MUSIC_VOL_STYLE, getVolStyleFromVol(music_vol));
        zsonObject.put(FIELD_RING_VOL_STYLE, getVolStyleFromVol(ring_vol));
        return zsonObject;
    }

    void updateStaticForm() {
        if (m_formId != -1) {
            updateVolumeForm(m_formId);
        }
    }

    @Override
    public void onInactive() {
        super.onInactive();
        HiLog.debug(LABEL_LOG, "update form %{public}d", m_formId);
        updateStaticForm();
    }

    void updateVolumeForm(long formId) {
        FormBindingData formBindingData = new FormBindingData(getVolumeFormData());
        // 调用updateForm接口去更新对应的卡片，仅更新入参中携带的数据信息，其他信息保持不变
        try {
            updateForm(formId, formBindingData);
        } catch (FormException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCastTempForm(long formId) {
        super.onCastTempForm(formId);
        HiLog.debug(LABEL_LOG, "cast form, id %{public}d", formId);
    }

    // 读取持久化的formid
    long getFormId() {
        if (m_databaseHelper == null || m_preferences == null) {
            m_databaseHelper = new DatabaseHelper(getApplicationContext()); // context入参类型为ohos.app.Context。
            String fileName = "form"; // fileName表示文件名，其取值不能为空，也不能包含路径，默认存储目录可以通过context.getPreferencesDir()获取。
            m_preferences = m_databaseHelper.getPreferences(fileName);
        }

        return m_preferences.getLong("formId", -1);
    }

    // 写入持久化的formid
    void setFormId(long formId) {
        if (m_databaseHelper == null || m_preferences == null) {
            m_databaseHelper = new DatabaseHelper(getApplicationContext()); // context入参类型为ohos.app.Context。
            String fileName = "form"; // fileName表示文件名，其取值不能为空，也不能包含路径，默认存储目录可以通过context.getPreferencesDir()获取。
            m_preferences = m_databaseHelper.getPreferences(fileName);
        }
        m_preferences.putLong("formId", formId);
        m_preferences.flush();
    }

    @Override
    protected void onEventNotify(Map<Long, Integer> formEvents) {
        super.onEventNotify(formEvents);
        HiLog.debug(LABEL_LOG, "onEventNotify");
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        HiLog.debug(LABEL_LOG, message);
        ZSONObject zsonObject = ZSONObject.stringToZSON(message);
        HiLog.debug(LABEL_LOG, "Event message: %{public}s, formId %{public}d", zsonObject.getString("message"), formId);
        if ("ACTION.SWITCH".equals(zsonObject.getString("action"))) {
            switch_mute();
        }
        updateVolumeForm(formId);
    }

    void subscribeCommonEvent() {
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); // 亮屏事件
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        CommonEventSubscriber subscriber = new CommonEventSubscriber(subscribeInfo) {
            @Override
            public void onReceiveEvent(CommonEventData commonEventData) {
                updateStaticForm();
            }
        };
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            HiLog.error(LABEL_LOG, "Exception occurred during subscribeCommonEvent invocation.");
        }
    }

    void unsubscribeCommonEvent() {
        try {
            CommonEventManager.unsubscribeCommonEvent(m_subscriber);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

}
